package com.cjm.one.custom.service;

import com.cjm.one.custom.config.EmailProperties;
import jakarta.annotation.Resource;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

@Service
public class MailService {
    @Resource
    private JavaMailSender javaMailSender;
    @Resource
    private EmailProperties emailPropertis;
    /**
     * @description: 发送简单邮件
     * @author: cjm
     * @date: 2025/3/9 21:26
     * @param: [email, subject, text]
     * @return: void
     **/
    public  void sendSimpleMail(String toEmail, String subject, String text) throws MessagingException {
        JavaMailSenderImpl sender = new JavaMailSenderImpl();
        // 创建一个 MIME 格式的邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        // 使用 MimeMessageHelper 来更方便地设置邮件内容和属性，第二个参数为 true 表示支持多部分内容（如包含图片等）
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
        messageHelper.setFrom(emailPropertis.getMailFrom());
        messageHelper.setTo(toEmail);
        messageHelper.setSubject(subject);
        messageHelper.setText(text);
        // 设置抄送人
        messageHelper.setCc(emailPropertis.getMailCc());
        javaMailSender.send(mimeMessage);
    }

    public void sendHtmlMail(String toEmail, String subject, String html) throws MessagingException {
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(emailPropertis.getMailFrom());
        helper.setTo(toEmail);
        helper.setSubject(subject);
        helper.setText(html, true);
        javaMailSender.send(message);
    }

}
